package net.esj.basic.utils;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;

import net.esj.basic.core.engine.config.MelonConfig;

import org.apache.commons.io.FileUtils;

public class RichTextUtils {

	/**
	 * 保存富文本框内容
	 * @param pages 每页内容
	 * @param fileName 文件名前缀
	 * @param fileDir 文件路径
	 * @param filePostFix 文件名后缀
	 * @throws IOException 
	 */
	public static void save(String[] pages,String fileName,String fileDir,String filePostFix) throws IOException{
		File dir = new File(fileDir);
		if(!dir.exists()){
			dir.mkdirs();
		}
		for(int i=0;i<pages.length;i++){
			File f = new File(fileDir, fileName+"_"+(i+1)+"."+filePostFix);
			FileUtils.writeStringToFile(f, pages[i]);
		}
	}
	
	/**
	 * 删除富文本内容
	 * @param fileNamePerFix 文件名前缀
	 * @param fileDir 文件路径
	 */
	public static void delete(final String fileNamePerFix,String fileDir){
		File dir = new File(fileDir);
		if(!dir.exists()){
			return ;
		}
		File[] pages = dir.listFiles(new FilenameFilter() {
			
			@Override
			public boolean accept(File dir, String name) {
				return name.startsWith(fileNamePerFix);
			}
		});
		for(File f : pages){
			f.delete();
		}
	}
	
	public static String  find(final String fileNamePerFix,String fileDir,String pageSpliter) throws IOException{
		File dir = new File(fileDir);
		if(!dir.exists()){
			return "";
		}
		StringBuilder content = new StringBuilder();
		File[] pages = dir.listFiles(new FilenameFilter() {
			
			@Override
			public boolean accept(File dir, String name) {
				return name.startsWith(fileNamePerFix);
			}
		});
		if(pages.length<=0){
			return "";
		}
		Arrays.sort(pages, 0, pages.length-1, new Comparator<File>() {

			@Override
			public int compare(File o1, File o2) {
				return getPager(o1.getName())-getPager(o2.getName());
			}

		});
		for(File f: pages){
			content.append(FileUtils.readFileToString(f));
			content.append(pageSpliter);
		}
		return content.substring(0, content.length()-pageSpliter.length());
	}
	
	private static int getPager(String filename){
		String name = filename.substring(0, filename.lastIndexOf("."));
		String k = name.substring(name.lastIndexOf("_"));
		if(StringUtils.hasText(k)){
			try{
				return Integer.valueOf(k);
			}catch(NumberFormatException e){
				return 0;
			}
		}
		return 0;
	}
	
}
